package com.yangjiayu;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * @Classname ServiceLogAspect
 * @Description TODO
 * @Date 2025/8/12 20:46
 * @Created by YangJiaYu
 */
@Component
@Slf4j
@Aspect
public class ServiceLogAspect {

    @Around("execution(* com.yangjiayu.service.impl..*.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
//        long startTime = System.currentTimeMillis();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        Object result = joinPoint.proceed();   // 执行业务方法

//        long endTime = System.currentTimeMillis();
        stopWatch.stop();

//        long takeTime = endTime - startTime;

        String signature = joinPoint.getTarget().getClass().getName()
            + "." + joinPoint.getSignature().getName();

        long takeTime =  stopWatch.getTotalTimeMillis();

        if (takeTime > 3000) {
            log.error("{} 耗时偏长 {} 毫秒", signature, takeTime);
        } else if (takeTime > 2000) {
            log.warn("{} 耗时中等 {} 毫秒", signature, takeTime);
        } else {
            log.info("{} 耗时 {} 毫秒", signature, takeTime);
        }

        return result;   // ✅ 把真正的结果返回
    }
}
